package com.bill.common.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

@SuppressWarnings("serial")
public class AppConfigUtils extends Properties {
	private static AppConfigUtils instance = new AppConfigUtils();
	private static final Logger LOGGER = Logger.getLogger(AppConfigUtils.class);
	
	protected AppConfigUtils() {
		InputStream inp = AppConfigUtils.class.getResourceAsStream("/config.properties");
		try {
			if (inp!=null) {
				load(inp);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static AppConfigUtils getInstance() {
		return instance;
	}

	/**
	 * Retrieves the physical path by the given abstract path.
	 * @param relativePath
	 * @return the physical path
	 */
	public static String getPhysicPath(String relativePath) {
		
		
		String physicPath = null;
		
		if (relativePath==null) {
			relativePath ="";
		}else{
			relativePath=relativePath.replaceAll("%20", " ");
		}

		if (new File(relativePath).isAbsolute()) {//绝对路径
			physicPath = relativePath;
			
		} else {//相对路径
			ServletContext servletContext = null;
			try {servletContext=ServletActionContext.getServletContext();} catch(Exception ex){
				LOGGER.info(ex);
			}
			if (servletContext != null) {//相对webapp下路径
				physicPath = servletContext.getRealPath(relativePath);
			} else {//相对classpath下路径
				physicPath = AppConfigUtils.class.getResource("/").getPath()+relativePath;
			}
		}
		
		physicPath=physicPath.replaceAll("%20", " ");
		
		try {
			physicPath=new String(physicPath.getBytes("ISO-8859-1"),"gb2312");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		File file = new File(physicPath);
		if (!file.exists()) {//如果文件夹不存在则创建
			file.mkdirs();
		}
		return physicPath;
	}

	/**
	 * 获取配置文件里的配置路径.
	 * @param paramName		配置文件里的参数名
	 * @param defaultPath   默认的路径
	 * @return
	 */
	public static String getConfigPath(final String paramName, final String defaultPath) {
		String basePath = "";
		if (instance!=null && instance.containsKey(paramName)) {
			basePath = instance.getProperty(paramName);
		}
		if (StringUtils.isEmpty(basePath)) {
			basePath = defaultPath;
		}
		
		basePath=getPhysicPath(basePath);
		basePath=basePath.replace("%20", " ");
		
		return basePath;
	}

}
